package com.xagent.engine.hook.enhance.v1;

import com.xagent.core.Properties;
import com.xagent.engine.context.inter.Context;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: 4ut15m
 * 通用hook
 * */
public class CommonV1Adapter extends ClassVisitor implements Opcodes {
    private String className;
    private Context context;

    public CommonV1Adapter() {
        super(Properties.COMMON_ASM_VERSION);
    }

    public CommonV1Adapter(Context context, String className, ClassVisitor classVisitor) {
        super(Properties.COMMON_ASM_VERSION, classVisitor);
        this.context = context;
        this.className = className;
    }

    public CommonV1Adapter(ClassVisitor classVisitor) {
        super(Properties.COMMON_ASM_VERSION, classVisitor);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
        String method = descriptor;
        if (method.contains("<init>")) {
            method = name;
        } else {
            Matcher matcher = Pattern.compile("(\\([a-zA-Z;/\\[]*\\))(.*)").matcher(method);
            if (matcher.find()) {
                method = name + matcher.group(1);
            }
        }
        for (String key : context.getConfig().getPolicyMap().keySet()) {
            if (context.getConfig().getPolicyMap().get(key).containsKey(className) && context.getConfig().getPolicyMap().get(key).get(className).needEnhance(method)) {
                mv = new CommonAdviceAdapter(mv, access, name, descriptor,className,context.getConfig().getPolicyMap().get(key).get(className).getAMethodInfo(method));
            }
        }

//        mv.visitEnd();
        return mv;
    }
}
